package com.tanhua.autoconfig.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.autoconfig.properties.SmsProperties;


/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/25 21:23
 *
 *  1. 定义模板对象SmsTemplate
 *  2. 定义自动装配类TanhuaAutoConfiguration;
 *  3. 添加装配文件 META-INF/spring.factories
 */


public class SmsTemplate {
    // 引入属性
    private SmsProperties smsProperties;

    // 通过构造方法将从文件中读取出来的
    public SmsTemplate(SmsProperties smsProperties){
        this.smsProperties = smsProperties;
    }

    /**
     * 发送验证码短信
     * @param mobile
     * @param code
     */
    public void sendSms(String mobile, String code){


        try {
            // 配置阿里云
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(smsProperties.getAccessKey())
                    // 您的AccessKey Secret
                    .setAccessKeySecret(smsProperties.getSecret());
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplateCode())
                    .setTemplateParam("{\"code\":\""+ code +"\"}");
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            if("OK".equals(response.getBody())){
                System.out.println("code send success");
            }
            System.out.println(response.getBody().getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
